<!--  -->
<template>
  <div class="app-container">
    <el-form inline size="small">
      <!-- 左边为新增按钮 中间是 客户名称、选择日期范围  右侧为查询按钮 -->
      <el-button
        class="mr10"
        type="primary"
        size="small"
        @click="onAddClick"
        icon="el-icon-plus"
      >新增
      </el-button>
      <el-form-item label="订单编号">
        <el-input
          v-model="params.salseOrderCode"
          clearable
          placeholder="请输入订单编号"
        ></el-input>
      </el-form-item>
      <!-- 销售员 -->
      <el-form-item label="销售员">
        <el-input
          v-model="params.salseName"
          placeholder="请输入销售员名称"
        ></el-input>
      </el-form-item>
      <!-- 平台渠道 选择器 使用维护的数组 -->
      <el-form-item label="平台渠道">
        <el-select
          v-model="params.platformChannels"
          clearable
          placeholder="请选择"
        >
          <el-option
            v-for="item in platformChannel"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <!--是否扣库存 是、否 -->
      <el-form-item label="是否扣库存" clearable>
        <el-select v-model="params.deductStock" clearable placeholder="请选择">
          <!-- 是否 -->
          <el-option label="是" value="是"></el-option>
          <el-option label="否" value="否"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="单据日期">
        <el-date-picker
          type="daterange"
          v-model="invoicesDate"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
      </el-form-item>
      <!-- 交货日期 -->
      <el-form-item label="交货日期">
        <el-date-picker
          type="daterange"
          value-format="yyyy-MM-dd"
          v-model="deliveryDate"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-button
        class="ml10"
        @click="getList"
        type="primary"
        size="small"
        icon="el-icon-search"
      >查询
      </el-button>
    </el-form>
    <el-table
      :data="data"
      border
      stripe
      style="width: 100%; margin-top: 10px"
      @row-dblclick="handleSelect"
    >
      <el-table-column prop="salseOrderCode" label="订单编号"/>
      <el-table-column prop="clientName" label="客户名称" width="150px"/>
      <el-table-column prop="salseName" label="销售员"/>
      <el-table-column prop="invoicesDate" label="单据日期"/>
      <el-table-column prop="deliveryDate" label="交货日期"/>
      <el-table-column prop="platformChannels" label="平台渠道"/>
      <el-table-column prop="deductStock" label="是否扣库存"/>
      <el-table-column prop="orderAmount" label="订单金额"/>
      <el-table-column label="操作" width="300">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            @click="handlePrintForm(scope.row)"
          >打印
          </el-button>
          <el-button
            type="primary"
            size="mini"
            @click="handleEditAddForm(scope.row)"
          >编辑
          </el-button>
          <el-button type="primary" size="mini" @click="handleView(scope.row)"
          >查看
          </el-button>
          <el-button type="danger" size="mini" @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="page">
      <el-row>
        <el-col>
          当前页金额：<font style="color: orange">￥{{ pageTotal }}</font>
          总金额：<font style="color: orange">￥{{ totalPrice }}</font>
        </el-col>
      </el-row>
      <el-pagination
        @size-change="onSizeChange"
        @current-change="onCurrentPageChange"
        :current-page="params.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="params.total"
      ></el-pagination>
    </div>
    <el-dialog
      :close-on-click-modal="false"
      title="订单新增"
      width="900px"
      append-to-body
      class="form-container"
      :visible.sync="visible"
    >
      <el-form
        inline
        ref="form"
        size="small"
        :model="addForm"
        :rules="rules"
        :disabled="isView"
        label-width="7em"
        class="add-form"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="订单编号"
              prop="salseOrderCode"
              class="salseOrderCode"
              :class="{
                'is-required': !addForm.isAutoGenerate,
              }"
            >
              <div style="display: flex; align-items: center">
                <el-input
                  v-model="addForm.salseOrderCode"
                  placeholder="请输入订单编号"
                />
                <!-- 是否自动生成开关 -->
                <el-switch
                  style="margin-left: 10px"
                  @change="onAutoGenerateChange"
                  v-model="addForm.isAutoGenerate"
                />
                <span style="flex: 1">自动生成</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="clientName">
              <el-select
                v-model="addForm.clientName"
                filterable
                :remote="true"
                placeholder="请选择供应商"
                style="width: 86%"
                :remote-method="(query) => querySearch(query, 'client')"
                @change="(query) => handleSelectInput(query, 'client')"
                :loading="clientLoading"
              >
                <el-option
                  v-for="item in clientList"
                  :key="item.value"
                  :label="item.clientName"
                  :value="item.clientName"
                />
              </el-select>
              <i
                class="el-icon-search"
                v-if="!isView"
                @click="showSelectClientDialog = true"
                style="
                  margin-left: 10px;
                  font-size: 20px;
                  font-weight: bold;
                  cursor: pointer;
                "
              ></i>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <!-- 客户电话 -->
            <el-form-item label="客户电话" prop="tel">
              <el-input
                v-model="addForm.tel"
                placeholder="请输入客户电话"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!--客户邮箱 -->
            <el-form-item label="客户邮箱" prop="email">
              <el-input
                v-model="addForm.email"
                placeholder="请输入客户邮箱"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 客户地址，文本域 2行 -->
            <el-form-item label="客户地址" style="width: 100%" prop="address">
              <el-input
                type="textarea"
                :rows="2"
                style="width: 200px"
                v-model="addForm.address"
                placeholder="请输入客户地址"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="销售单名称" prop="salseOrderName">
              <el-input
                v-model="addForm.salseOrderName"
                placeholder="请输入销售单名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 订单日期 -->
            <el-form-item label="订单日期" prop="invoicesDate">
              <el-date-picker
                v-model="addForm.invoicesDate"
                type="date"
                placeholder="选择日期"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!--交货日期 -->
            <el-form-item label="交货日期" prop="deliveryDate">
              <el-date-picker
                v-model="addForm.deliveryDate"
                type="date"
                placeholder="选择日期"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="业务员" prop="salseName">
              <el-input
                v-model="addForm.salseName"
                placeholder="请输入业务员名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订单金额" prop="orderAmount">
              <el-input
                v-model="addForm.orderAmount"
                placeholder="请输入订单金额"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 实收金额 -->
            <el-form-item label="实收金额" prop="actualAmount">
              <el-input
                v-model="addForm.actualAmount"
                placeholder="请输入实收金额"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="报价单名称" prop="quoteOrderName">
              <el-select
                v-model="addForm.quoteOrderName"
                filterable
                :remote="true"
                placeholder="请选择报价单"
                style="width: 86%"
                :remote-method="(query) => querySearch(query, 'quote')"
                @change="(query) => handleSelectInput(query, 'quote')"
                :loading="quoteLoading"
              >
              </el-select>
              <i
                class="el-icon-search"
                v-if="!isView"
                @click="showSelectQuoteDialog = true"
                style="
                  margin-left: 10px;
                  font-size: 20px;
                  font-weight: bold;
                  cursor: pointer;
                "
              ></i>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否扣库存" prop="deductStock">
              <el-radio-group v-model="addForm.deductStock">
                <el-radio label="是">是</el-radio>
                <el-radio label="否">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单据状态" prop="salesStatus">
              <el-radio-group v-model="addForm.salesStatus">
                <el-radio label="0" value="0">进行中</el-radio>
                <el-radio label="1" value="1">已完成</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <!-- 附件 -->
            <el-form-item label="附件" prop="attachment" v-if="visible">
              <file-upload v-model="addForm.filename"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="平台渠道" prop="platformChannels">
              <el-select
                v-model="addForm.platformChannels"
                placeholder="请选择平台渠道"
              >
                <el-option
                  v-for="item in platformChannel"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 备注 -->
            <el-form-item label="备注" prop="remark">
              <el-input
                type="textarea"
                :rows="2"
                style="width: 200px"
                v-model="addForm.remark"
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 分割线 -->
      <div style="height: 1px; background-color: #ebeef5; margin: 20px 0"></div>

      <!-- titile:商品信息，右边是选择商品按钮 -->
      <div
        style="
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-bottom: 10px;
        "
      >
        <div style="font-size: 16px; font-weight: bold">商品信息</div>
        <el-button
          type="primary"
          size="small"
          icon="el-icon-plus"
          @click="onAddGoodsClick"
          v-if="!isView"
        >选择商品
        </el-button>
      </div>
      <!-- 表格 -->
      <!-- 序号、商品编码、商品名称、规格型号、单位、数量、单价、小计、备注、操作（编辑、删除） -->
      <el-table :data="addForm.orderDetails" border stripe>
        <el-table-column type="index" width="50"/>
        <el-table-column prop="itemCode" label="商品编码"/>
        <el-table-column prop="itemName" label="商品名称"/>
        <el-table-column
          label="产品物料图片"
          prop="itemImage"
          align="center"
          width="100px"
        >
          <template slot-scope="scope">
            <el-image
              style="width: 50px; height: 50px; margin-bottom: -4px"
              :src="`${baseUrl}` + scope.row.itemImage"
            >
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="specification" label="规格型号"/>
        <el-table-column prop="unitOfMeasure" label="单位"/>
        <el-table-column prop="num" label="数量"/>
        <el-table-column prop="unitPrice" label="单价"/>
        <el-table-column prop="total" label="小计"/>
        <el-table-column prop="remark" label="备注"/>
        <el-table-column label="操作" width="150px" v-if="!isView">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              @click="handleEditGoods(scope.row, scope.$index)"
            >编辑
            </el-button>
            <el-button
              type="danger"
              size="mini"
              @click="handleDeleteGoods(scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <template v-if="!isView">
          <el-button type="primary" @click="submit" v-if="!addForm.salseOrderId"
          >新增
          </el-button>
          <el-button type="primary" @click="submit" v-else>修改</el-button>
        </template>
      </div>
    </el-dialog>
    <!-- 选择商品弹窗 -->
    <!-- 商品编码、商品名称、规格型号、单位、数量、单价、小计、备注 -->
    <el-dialog
      :close-on-click-modal="false"
      title="选择商品"
      :visible.sync="showAddGoodsDialog"
      width="500px"
    >
      <el-form
        label-width="6em"
        ref="addGoodsRef"
        size="small"
        :model="addGoodsForm"
        :rules="addGoodsRules"
      >
        <el-form-item label="商品编码" prop="itemCode">
          <el-input
            disabled
            style="width: 90%"
            v-model="addGoodsForm.itemCode"
            clearable
            placeholder="请输入商品编码"
          ></el-input>
          <i
            class="el-icon-search"
            @click="showSelectGoodsDialog = true"
            style="
              margin-left: 10px;
              font-size: 20px;
              font-weight: bold;
              cursor: pointer;
            "
          ></i>
        </el-form-item>

        <el-form-item label="商品名称" prop="itemName">
          <el-input
            disabled
            v-model="addGoodsForm.itemName"
            clearable
            placeholder="请输入商品名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="产品图片" prop="itemImage">
          <ImageUpload
            :value="`${baseUrl}` + addGoodsForm.itemImage"
            @onUploaded="handleImgUplaoded"
            @onRemoved="handleImgRemoved"
            :limit="1"
            :fileSize="1"
            :fileType="['png', 'jpg']"
            title="图片大小不超过156kb，图片格式为PNG"
          />
        </el-form-item>
        <el-form-item label="规格型号" prop="specification">
          <el-input
            v-model="addGoodsForm.specification"
            clearable
            disabled
            placeholder="请输入规格型号"
          ></el-input>
        </el-form-item>

        <el-form-item label="单位" prop="unitOfMeasure">
          <el-input
            disabled
            v-model="addGoodsForm.unitOfMeasure"
            clearable
            placeholder="请输入单位"
          ></el-input>
        </el-form-item>

        <el-form-item label="数量" prop="num">
          <el-input
            v-model="addGoodsForm.num"
            clearable
            type="number"
            placeholder="请输入数量"
          ></el-input>
        </el-form-item>

        <el-form-item label="单价" prop="unitPrice">
          <el-input
            v-model="addGoodsForm.unitPrice"
            clearable
            type="number"
            placeholder="请输入单价"
          ></el-input>
        </el-form-item>

        <el-form-item label="小计" prop="total">
          <el-input
            disabled
            v-model="addGoodsForm.total"
            clearable
            placeholder="请输入小计"
          ></el-input>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="addGoodsForm.remark"
            clearable
            placeholder="请输入备注"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showAddGoodsDialog = false">取消</el-button>
        <el-button class="ml10" @click="addGoods" type="primary" size="small"
        >确认
        </el-button
        >
      </div>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      width="1100px"
      :visible.sync="showSelectGoodsDialog"
    >
      <mditem :isComponent="true" @select="onSelectGoods"/>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      width="1100px"
      :visible.sync="showSelectClientDialog"
    >
      <client :isComponent="true" @select="onSelectClient"/>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      width="1100px"
      :visible.sync="showSelectQuoteDialog"
    >
      <quote :isComponent="true" @select="onSelectQuote"/>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      :destory-on-close="true"
      title="打印"
      width="1100px"
      :visible.sync="showPrintDialog"
    >
      <RIframe v-if="showPrintDialog" :src="currentPrintUrl"/>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request";
import {getToken} from "@/utils/auth";
import mditem from "@/views/mes/md/mditem/index.vue";
import client from "@/views/mes/md/client/index.vue";
import quote from "@/views/mes/quote/index.vue";
import moment from "moment";
import fileUpload from "@/components/FileUpload/index.vue";
import {genCode} from "@/api/system/autocode/rule";
import RIframe from "@/components/iFrame/index.vue";

import _ from "lodash";
import {listClient} from "@/api/mes/md/client";
import {getQuoteItem, listQuote} from "@/api/mes/md/quote";

export default {
  mounted() {
    this.getList();
    request({
      url: "/mes/wm/salseOrder/getTotalPrice",
      method: "get",
    }).then((res) => {
      this.totalPrice = res.data;
    });
  },
  watch: {
    // addGoodsForm.total
    "addGoodsForm.num"(val) {
      this.addGoodsForm.total = val * this.addGoodsForm.unitPrice;
    },
    "addGoodsForm.unitPrice"(val) {
      this.addGoodsForm.total = val * this.addGoodsForm.num;
    },
  },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      pageTotal: 0.0,
      totalPrice: 0.0,
      currentPrintUrl: "",
      clientList: [],
      quoteList: [],
      showPrintDialog: false,
      clientLoading: false,
      quoteLoading: false,
      showSelectGoodsDialog: false,
      showSelectClientDialog: false,
      showSelectQuoteDialog: false,
      showAddGoodsDialog: false,
      invoicesDate: [],
      deliveryDate: [],
      addGoodsRules: {
        itemCode: [
          {required: true, message: "请输入商品编码", trigger: "blur"},
        ],
        itemName: [
          {required: true, message: "请输入商品名称", trigger: "blur"},
        ],
        // specification: [
        //   { required: true, message: "请输入规格型号", trigger: "blur" },
        // ],
        unitOfMeasure: [
          {required: true, message: "请输入单位", trigger: "blur"},
        ],
        num: [{required: true, message: "请输入数量", trigger: "blur"}],
        unitPrice: [{required: true, message: "请输入单价", trigger: "blur"}],
        remark: [{required: false, trigger: "blur"}],
      },
      rules: {
        // 判断自动生成是否为true，如果为true则不需要验证
        salseOrderCode: [
          {
            required: true,
            message: "请输入订单编号",
            trigger: "blur",
          },
        ],
        // 客户电话
        tel: [{required: true, message: "请输入客户电话", trigger: "blur"}],
        // 客户邮箱
        email: [{required: true, message: "请输入客户邮箱", trigger: "blur"}],
        // 客户地址
        address: [
          {required: true, message: "请输入客户地址", trigger: "blur"},
        ],
        clientName: [
          {required: true, message: "请选择客户", trigger: "blur"},
        ],
        salseName: [
          {required: true, message: "请输入业务员", trigger: "blur"},
        ],
        invoicesDate: [
          {required: true, message: "请选择订单日期", trigger: "blur"},
        ],
        deliveryDate: [
          {required: true, message: "请选择交货日期", trigger: "blur"},
        ],
        platformChannels: [
          {required: true, message: "请选择平台渠道", trigger: "blur"},
        ],
        deductStock: [
          {required: true, message: "请选择是否扣库存", trigger: "blur"},
        ],
        salesStatus: [
          {required: true, message: "请选择单据状态", trigger: "blur"},
        ],
        orderAmount: [
          {required: true, message: "请输入订单金额", trigger: "blur"},
        ],
        actualAmount: [
          {required: true, message: "请输入实收金额", trigger: "blur"},
        ],
      },
      params: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        wmProductSalseOrder: {},
      },
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/upload",
      },
      addForm: {
        orderDetails: [],
      },
      platformChannel: [
        {
          value: "线下",
          label: "线下",
        },
        {
          value: "1688",
          label: "1688",
        },
        {
          value: "赠送",
          label: "赠送",
        },
        {
          value: "淘宝",
          label: "淘宝",
        },
        {
          value: "拼多多",
          label: "拼多多",
        },
      ],
      fileList: [],
      goodsTableData: [],
      data: [],
      addGoodsForm: {
        itemCode: "",
        itemName: "",
        specification: "",
        unitOfMeasure: "",
        num: "",
        unitPrice: "",
        total: "",
        remark: "",
      },
      visible: false,
      isView: false,
      isGoodsEdit: false,
    };
  },

  methods: {
    //图片上传成功
    handleImgUplaoded(imgUrl) {
      this.addGoodsForm.itemImage = imgUrl;
    },
    //图片移除
    handleImgRemoved(imgUrl) {
      this.addGoodsForm.itemImage = null;
    },
    querySearch(query, type) {
      if (type == "client") {
        if (query !== "") {
          listClient({
            clientName: query,
          }).then((response) => {
            this.clientLoading = false;
            this.clientList = response.rows;
          });
        } else {
          this.clientList = [];
        }
      } else if (type == "quote") {
        if (query !== "") {
          listQuote({
            quoteOrderName: query,
          }).then((response) => {
            this.quoteLoading = false;
            this.quoteList = response.rows;
          });
        } else {
          this.quoteList = [];
        }
      }
    },
    handleSelectInput(val, type) {
      //  获取到对应对象
      if (type == "client") {
        const client = this.clientList.find((item) => item.clientName === val);
        this.onSelectClient(client);
      } else if (type == "quote") {
        const quote = this.quoteList.find(
          (item) => item.quoteOrderName === val
        );
        this.onSelectQuote(quote);
      }
    },
    handleView(row) {
      this.isView = true;
      //http://localhost:8080/mes/wm/salseOrder/{{salseOrderId}}
      request({
        url: "/mes/wm/salseOrder/" + row.salseOrderId,
        method: "get",
      }).then((res) => {
        this.addForm = res.data;
        this.visible = true;
      });
    },
    onAutoGenerateChange(val) {
      if (this.addForm.isAutoGenerate) {
        genCode("SALE_CODE").then((res) => {
          console.log("====================================");
          console.log(res);
          console.log("====================================");
          this.$set(this.addForm, "salseOrderCode", res);
        });
      } else {
        this.addForm.salseOrderCode = "";
      }
    },
    handleSelect(row) {
      this.$emit("select", row);
    },
    handlePrintForm(row) {
      this.isView = false;
      //http://localhost:8080/mes/wm/purchaseOrder/{{purchaseOrderId}}
      this.currentPrintUrl = `${location.origin}/prod-api/jmreport/view/923558633647824896?&salseOrderId=${row.salseOrderId}`;
      this.showPrintDialog = true;
    },
    handleEditAddForm(row) {
      this.isView = false;
      //http://localhost:8080/mes/wm/salseOrder/{{salseOrderId}}
      request({
        url: "/mes/wm/salseOrder/" + row.salseOrderId,
        method: "get",
      }).then((res) => {
        this.addForm = res.data;
        let orderAmount = 0
        this.addForm.orderDetails.map((order) => {
          orderAmount = orderAmount + order.total
        })
        this.$set(this.addForm, 'orderAmount', orderAmount)
        this.fileList = [];
        if (this.addForm.filename) {
          this.fileList = this.addForm.filename.split(",").map((item) => {
            return {
              name: item,
              url:
                process.env.VUE_APP_BASE_API +
                "/common/download?fileName=" +
                item,
            };
          });
        }
        this.visible = true;
      });
    },
    handleEditGoods(row, index) {
      this.addGoodsForm = _.cloneDeep({
        ...row,
        index,
      });
      this.showAddGoodsDialog = true;
      this.isGoodsEdit = true;
    },
    handleFileSuccess(response, file, fileList) {
      console.log("====================================");
      console.log(response);
      console.log("====================================");
      this.upload.open = false;
      this.upload.isUploading = false;
      this.fileList[0] = {
        name: response.fileName,
        url:
          process.env.VUE_APP_BASE_API +
          "/common/download?fileName=" +
          response.fileName,
      };
      if (this.addForm.filename) {
        this.addForm.filename = this.addForm.filename + "," + response.fileName;
      } else {
        this.addForm.filename = response.fileName;
      }
      // this.$refs.upload.clearFiles();
    },
    handleFileRemove(file, fileList) {
      console.log("====================================");
      console.log(fileList);
      console.log("====================================");
    },
    onSelectGoods(goods) {
      this.showSelectGoodsDialog = false;
      this.addGoodsForm.itemId = goods.itemId;
      this.addGoodsForm.itemCode = goods.itemCode;
      this.addGoodsForm.itemName = goods.itemName;
      this.addGoodsForm.itemImage = goods.itemImage;
      this.addGoodsForm.specification = goods.specification;
      this.addGoodsForm.unitOfMeasure = goods.unitOfMeasure;
      this.addGoodsForm.warehouseId = goods.warehouseId;
      this.addGoodsForm.warehouseCode = goods.warehouseCode;
      this.addGoodsForm.warehouseName = goods.warehouseName;
      this.addGoodsForm.locationId = goods.locationId;
      this.addGoodsForm.locationCode = goods.locationId;
      this.addGoodsForm.locationName = goods.locationName;
      this.addGoodsForm.areaId = goods.areaId;
      this.addGoodsForm.areaCode = goods.areaCode;
      this.addGoodsForm.areaName = goods.areaName;
    },
    onSelectClient(client) {
      console.log(client);
      this.showSelectClientDialog = false;
      this.addForm.clientCode = client.clientCode;
      this.addForm.clientName = client.clientName;
      this.$set(this.addForm, 'tel', client.tel);
      this.$set(this.addForm, 'email', client.email);
      this.$set(this.addForm, 'address', client.address);
    },
    onSelectQuote(quote) {
      console.log("quote: "+JSON.stringify(quote));
      this.showSelectQuoteDialog = false;
      getQuoteItem(quote.quoteCode).then((res) => {
        this.addForm.orderDetails = res.data;
        let orderAmount = 0;
        res.data.map((order) => {
          orderAmount = orderAmount + order.total;
        });
        this.$set(this.addForm, 'orderAmount', orderAmount);
      });
      this.addForm.quoteOrderCode = quote.quoteCode;
      this.addForm.quoteOrderName = quote.quoteName;
      this.$set(this.addForm, 'tel', quote.contactNo);
      this.$set(this.addForm, 'clientName', quote.customerName);
      this.$set(this.addForm, 'orderAmount', quote.total);
    },
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    onAddGoodsClick() {
      this.isGoodsEdit = false;
      // 清空
      this.addGoodsForm = {
        itemId:"",
        itemCode: "",
        itemName: "",
        specification: "",
        unitOfMeasure: "",
        num: "",
        unitPrice: "",
        total: "",
        remark: "",
      };
      this.showAddGoodsDialog = true;
    },
    addGoods() {
      this.$refs["addGoodsRef"].validate((valid) => {
        if (valid) {
          if (this.isGoodsEdit) {
            // 判断addForm是否有id

            if (this.addGoodsForm.salseOrderDetailId) {
              // 修改
              request({
                url: "/mes/wm/productSalseOrderDetail",
                method: "put",
                data: {...this.addGoodsForm},
              }).then((res) => {
                if (res.code === 200) {
                  this.$message({
                    type: "success",
                    message: "修改成功!",
                  });
                  this.addForm.orderDetails = this.addForm.orderDetails.map(
                    (item) => {
                      if (
                        item.salseOrderDetailId ===
                        this.addGoodsForm.salseOrderDetailId
                      ) {
                        return this.addGoodsForm;
                      }
                      return item;
                    }
                  );
                  let orderAmount = 0
                  this.addForm.orderDetails.map((order) => {
                    orderAmount = orderAmount + order.total
                  })
                  this.$set(this.addForm, 'orderAmount', orderAmount)
                  this.showAddGoodsDialog = false;
                } else {
                  this.$message({
                    type: "error",
                    message: res.msg,
                  });
                }
              });
              return;
            }

            if (!this.addForm.salseOrderId) {
              this.$set(
                this.addForm.orderDetails,
                this.addGoodsForm.index,
                this.addGoodsForm
              );
              this.showAddGoodsDialog = false;
            }
          } else {
            if (this.addForm.salseOrderId) {
              // 调接口直接添加
              request({
                url: `/mes/wm/productSalseOrderDetail/${this.addForm.salseOrderCode}/wmProductSalseOrderDetail`,
                method: "post",
                data: {
                  ...this.addGoodsForm,
                  salseOrderCode: this.addForm.salseOrderCode,
                },
              }).then((res) => {
                if (res.code === 200) {
                  this.$message({
                    type: "success",
                    message: "新增成功!",
                  });
                  request({
                    url: "/mes/wm/salseOrder/" + this.addForm.salseOrderId,
                    method: "get",
                  }).then((res) => {
                    this.addForm.orderDetails = res.data.orderDetails;
                    let orderAmount = 0
                    this.addForm.orderDetails.map((order) => {
                      orderAmount = orderAmount + order.total
                    })
                    this.$set(this.addForm, 'orderAmount', orderAmount)
                  });
                  this.showAddGoodsDialog = false;
                } else {
                  this.$message({
                    type: "error",
                    message: res.msg,
                  });
                }
              });
            } else {
              this.addForm.orderDetails.push({
                ...this.addGoodsForm,
              });
              this.showAddGoodsDialog = false;
            }
          }
        } else {
          return false;
        }
      });
    },
    handleDeleteGoods(row) {
      // 提示是否确认
      this.$confirm("是否确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //  如果不存在id，则直接删除这条
          if (!row.salseOrderDetailId) {
            this.addForm.orderDetails = this.addForm.orderDetails.filter(
              (item) => item !== row
            );
            let orderAmount = 0
            this.addForm.orderDetails.map((order) => {
              orderAmount = orderAmount + order.total
            })
            this.$set(this.addForm, 'orderAmount', orderAmount)
            return;
          }
          // http://localhost:8080/mes/wm/productSalseOrderDetail/{{salseOrderDetailId}}
          request({
            url: "/mes/wm/productSalseOrderDetail/" + row.salseOrderDetailId,
            method: "delete",
          }).then((res) => {
            if (res.code === 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.addForm.orderDetails = this.addForm.orderDetails.filter(
                (item) => item !== row
              );
              let orderAmount = 0
              this.addForm.orderDetails.map((order) => {
                orderAmount = orderAmount + order.total
              })
              this.$set(this.addForm, 'orderAmount', orderAmount)
            } else {
              this.$message({
                type: "error",
                message: res.msg,
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleDelete(row) {
      // 提示是否确认删除
      this.$confirm("是否确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // http://localhost:8080/mes/wm/salseOrder/{{salseOrderIds}}
          request({
            url: "/mes/wm/salseOrder/" + row.salseOrderId,
            method: "delete",
          }).then((res) => {
            if (res.code === 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.getList();
            } else {
              this.$message({
                type: "error",
                message: res.msg,
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    onAddClick() {
      this.isView = false;
      this.addForm = {
        orderDetails: [],
      };
      this.visible = true;
      this.addForm.isAutoGenerate = true;
      this.onAutoGenerateChange();
    },
    getList() {
      // startInvoicesDate 单据日期开始时间
      // endInvoicesDate 单据日期结束时间
      // startDeliveryDate 交货日期开始时间
      // endDeliveryDate 交货日期结束时间

      let params = {
        ...this.params,
      };
      if (this.invoicesDate.length > 0) {
        params.startInvoicesDate = moment(this.invoicesDate[0]).format(
          "YYYY-MM-DD"
        );
        params.endInvoicesDate = moment(this.invoicesDate[1]).format(
          "YYYY-MM-DD"
        );
      }
      if (this.deliveryDate.length > 0) {
        params.startDeliveryDate = moment(this.deliveryDate[0]).format(
          "YYYY-MM-DD"
        );
        params.endDeliveryDate = moment(this.deliveryDate[1]).format(
          "YYYY-MM-DD"
        );
      }
      request({
        url: "/mes/wm/salseOrder/list",
        method: "get",
        params,
      }).then((res) => {
        console.log("====================================");
        console.log(res);
        console.log("====================================");
        this.data = res.rows;
        this.params.total = res.total;
        let orderAmount = 0;
        this.data.map((item) => {
          orderAmount = orderAmount + item.orderAmount;
        });
        this.pageTotal = orderAmount;
      });
    },
    onSizeChange(val) {
      this.params.pageSize = val;
      this.getList();
    },
    onCurrentPageChange(val) {
      this.params.pageNum = val;
      this.getList();
    },
    submit() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.addForm.salseOrderId) {
            // 修改
            request({
              url: "/mes/wm/salseOrder",
              method: "put",
              data: {...this.addForm},
            }).then((res) => {
              if (res.code === 200) {
                this.$message({
                  type: "success",
                  message: "修改成功!",
                });
                this.visible = false;
                this.getList();
              } else {
                this.$message({
                  type: "error",
                  message: res.msg,
                });
              }
            });
            return;
          }
          // mes/wm/salseOrder
          request({
            url: "/mes/wm/salseOrder",
            method: "post",
            data: {...this.addForm},
          }).then((res) => {
            if (res.code === 200) {
              this.$message({
                type: "success",
                message: "新增成功!",
              });
              this.visible = false;
              this.getList();
            } else {
              this.$message({
                type: "error",
                message: res.msg,
              });
            }
          });
        } else {
          return false;
        }
      });
    },
  },

  components: {
    mditem,
    client,
    quote,
    fileUpload,
    RIframe,
  },

  computed: {},
};
</script>
<style lang="scss" scoped>
.page {
  text-align: right;
  margin-top: 10px;
}

::v-deep {
  .el-form .el-form--inline {
    display: flex;
    align-items: center;
    width: 100%;
    justify-content: space-between;
  }
}

.form-container {
  ::v-deep {
    .el-form-item {
      min-width: 290px;
      margin-bottom: 15px;
      display: inline-flex;
      align-items: center;
    }

    .el-form-item__content {
      display: inline-flex;
      align-items: center;
    }

    .el-input {
      width: 160px;
    }
  }
}
</style>
